#include <glob.h>

#include <caml/mlvalues.h>
#include <caml/alloc.h>
#include <caml/memory.h>
#include <caml/fail.h>

value glob_c(value pattern) {
  int i, gl_flags;
  glob_t gl;
  value matched_paths;

  CAMLparam1 (pattern);

  gl_flags = GLOB_BRACE | GLOB_TILDE;
  if (glob(String_val(pattern), gl_flags, NULL, &gl)) {
    globfree(&gl);
    CAMLreturn (caml_alloc(0 ,0));
  }

  matched_paths = caml_alloc(gl.gl_pathc, 0);
  for (i = 0; i < gl.gl_pathc; ++i) {
    Store_field(matched_paths, i, caml_copy_string(gl.gl_pathv[i]));
  }
  globfree(&gl);
  CAMLreturn (matched_paths);
}
